import * as apis from '@/apis/modules/merchantTrade.js';

const merchantTrade = {
	namespaced: true,
	state: {
		tradeList: [{}],
		pageNum: 1,
		hasData: false
	},
	mutations: {
		save(state, {field, payload}) {
		  if (Object.prototype.toString.call(payload) === '[object Object]') {
			state[field] = { ...state[field], ...payload }
		  } else {
			state[field] = payload
		  }
		}
	},
	actions: {
		getTradeList({ commit, state, dispatch }, {pageNum = 1} = {}) {
			dispatch('getCurrentSummary')
			
			apis.getTradeList({current: pageNum})
				.then(({data}) => {
					const {pages, records} = data
					let {tradeList} = state
					
					if (pageNum > 1) {
						tradeList = tradeList.concat(records)
					} else {
						tradeList = records || []
					}
					if (pages === pageNum || pages === 0) commit('save', {field: 'hasData', payload: false})
					
			    commit('save', {field: 'tradeList', payload: tradeList})
					commit('save', {field: 'pageNum', payload: pageNum})
				})
		},
		
		getCurrentSummary({commit, state}) {
			apis.getCurrentSummary()
				.then(({data}) => {
					const {tradeList} = state
					
					tradeList.unshift(data)
					
					commit('save', {field: 'tradeList', payload: tradeList})
				})
		}
	}
}

export default merchantTrade